/**
 * 高级图文相关服务
 * advancedNews-service.ts
 * @authors 杨兴洲（of2502）
 * @date    2017/5/17 0017 15:20
 * @version 1.0
 */
import AdvancedNews from "../model/advancedNews";
// import logger from "../util/logger";
interface Article {
    title: string,
    description: string,
    url: string,
    picurl: string
}

export default class AdvancedNewsService {

    static async createNews({appID, articles}: { appID: string, articles: Article[] }): Promise<any> {
        return await AdvancedNews.create({appID, articles})
    }

    static async deleteNews(newsID: string): Promise<any> {
        return await AdvancedNews.findByIdAndRemove(newsID)
    }

    static async updateNews({newsID, articles, index}: { newsID: string, articles: Article, index }): Promise<any> {
        let {articles: list} = await AdvancedNewsService.getDetail(newsID);
        if (list.length < index + 1) {
            return {
                errcode: "20101",
                errmsg: "index大于文章数"
            }
        }
        list[index] = articles;
        return await AdvancedNews.findByIdAndUpdate(newsID, {articles: list})
    }

    static async getDetail(newsID: string): Promise<any> {
        return await AdvancedNews.findById(newsID)
    }

    static async getList({appID, page = 1, pageSize = 20}): Promise<any> {
        const total = await AdvancedNews.count({appID});
        const list = await AdvancedNews.find({appID}, {"appID": 0})
            .sort({updatedAt: -1})
            .skip(pageSize * (page - 1)).limit(pageSize);
        return {total, list};
    }
}
